package api

import (
	"context"
	"gdmin/db"
	"gdmin/global"
	"gdmin/model"
	"gdmin/servlet"
	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/route"
	"strconv"
)

func LogApi(r *route.RouterGroup) {
	r.POST("/log/page", func(c context.Context, ctx *app.RequestContext) {
		var req servlet.LogQuery
		err := ctx.Bind(&req)
		if err != nil {
			servlet.FailWithMessage(err.Error(), ctx)
			return
		}

		var d []*servlet.LogResp
		tx := global.DB.Model(&model.Log{})

		if req.Method != "" {
			tx.Where("method = ?", req.Method)
		}
		if req.Path != "" {
			tx.Where("path like ?", req.Path)
		}
		if req.UserId != 0 {
			tx.Where("user_id =?", req.UserId)
		}
		if req.Body != "" {
			tx.Where("body like?", req.Body)
		}
		if req.QueryString != "" {
			tx.Where("query_string like?", req.QueryString)
		}

		page := db.CommonPage(&req.Pagination, &d, tx)

		for _, item := range d {
			id := userService.QueryUserById(strconv.Itoa(item.CreateUserId))
			if id != nil {

				item.UserName = id.Name
			}
		}

		servlet.OkWithData(ctx, page)

		return
	})
}
